package server;

import java.io.*;

public class Response {
    private static final int BUFFER_SIZE = 1024;
    private static final String ERROR_MESSAGE = "HTTP/1.1 404 File Not Found\r\n" +
            "Content-type: text/html\r\n" +
            "Content-Length: 23\r\n" +
            "\r\n" +
            "<h1>File Not Found</h1>";
    private OutputStream output;
    private Request request;
    public Response(OutputStream output) {
        this.output = output;
    }
    public void setRequest(Request request) {
        this.request = request;
    }
    public void sendStaticResource() throws IOException {
        FileInputStream fis = null;
        try {
            File file = new File(HttpServer.WEB_ROOT, this.request.getUri());
            if (file.exists() && file.isFile()) {
                PrintWriter printWriter = new PrintWriter(output);
                printWriter.println("HTTP/1.1 200 OK");
                printWriter.println("Content-Type:text/html;charset=utf-8");
                printWriter.println("Content-length: " + file.length());
                printWriter.println();
                printWriter.flush();
                fis = new FileInputStream(file);
                byte[] bytes = new byte[BUFFER_SIZE];
                int len = fis.read(bytes, 0, BUFFER_SIZE);
                while (len != -1) {
                    output.write(bytes, 0, len);
                    len = fis.read(bytes, 0, BUFFER_SIZE);
                }
                printWriter.close();
            } else {
                this.output.write(ERROR_MESSAGE.getBytes());
            }
        } catch (IOException e) {
          //  e.printStackTrace();
            this.output.write(ERROR_MESSAGE.getBytes());
            this.output.close();
        } finally {
            if (fis != null)
                fis.close();
        }
    }
}
